package io.zhengsh.nio.files;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class AsynchronousFileChannelDemo2 {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path path = Paths.get("/Users/zhengsh/" +
                "sourcecode.io/zhengsh-vvip/nio/src/main/resources/01.txt");
        AsynchronousFileChannel fileChannel = null;
        try {

            fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long position = 0;

        fileChannel.read(buffer, position, buffer,
                new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        System.out.println("result : " + result);
                        buffer.flip();

                        byte[] data = new byte[buffer.limit()];
                        buffer.get(data);
                        System.out.println(new String(data));
                        buffer.clear();

                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {

                    }
                });
        TimeUnit.SECONDS.sleep(1000);
    }
}
